package com.crocodileq.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.crocodileq.dto.Result;
import com.crocodileq.entity.Shop;
import com.crocodileq.mapper.ShopMapper;
import com.crocodileq.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crocodileq.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Result queryShopById(Long id) {
        //从redis中查询商铺信息
        String cacheShop = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_KEY + id);

        //缓存是否命中，命中则返回
        if(StrUtil.isNotBlank(cacheShop)){
            //反序列化
            Shop shop = JSONUtil.toBean(cacheShop, Shop.class);
            return Result.ok(shop);
        }

        //空值判断
        if(cacheShop != null){
            return Result.fail("店铺不存在");
        }

        //缓存未命中，查询数据库
        Shop shop = getById(id);

        //判断商铺是否存在，不存在则返回错误
        if(ObjectUtils.isEmpty(shop)){
            //缓存null，并设置过期时间
            stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,
                    "",
                    RedisConstants.CACHE_NULL_TTL,
                    TimeUnit.MINUTES
            );
            return Result.fail("店铺不存在");
        }

        //存在，缓存商铺信息
        stringRedisTemplate.opsForValue()
                .set(RedisConstants.CACHE_SHOP_KEY + id,
                        JSONUtil.toJsonStr(shop),
                        RedisConstants.CACHE_SHOP_TTL,
                        TimeUnit.MINUTES);

        //返回
        return Result.ok(shop);
    }
}
